package cn.b.sky.shop.storage.utils;


import cn.b.sky.shop.storage.Progress;
import cn.b.sky.shop.storage.ProgressListener;

import java.io.EOFException;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class ProgressAwareOutputStream extends FilterOutputStream {

    private final ProgressListener listener;
    private final Progress progress = new Progress();
    private volatile boolean cancelled = false;

    public ProgressAwareOutputStream(OutputStream out, long total, ProgressListener listener) {
        super(out);
        this.progress.setTotal(total);
        this.listener = listener;
    }

    @Override
    public void write(int b) throws IOException {
        if (cancelled) {
            throw new EOFException("Cancelled");
        }
        out.write(b);
        progress.addCompleted(1);
        if (listener != null) {
            listener.onProgress(progress);
        }
    }

    @Override
    public void write( byte[] b, int off, int len) throws IOException {
        if (cancelled) {
            throw new EOFException("Cancelled");
        }
        out.write(b, off, len);
        progress.addCompleted(len);
        if (listener != null) {
            listener.onProgress(progress);
        }
    }

    public void setTotal(long total) {
        this.progress.setTotal(total);
    }

    public void setCompleted(long completed) {
        this.progress.setCompleted(completed);
    }

    /**
     * cancel以后，会读取到流结束标识
     *
     * @return
     */
    public boolean cancel() {
        boolean c = this.cancelled;
        this.cancelled = true;
        return !c;
    }
}
